package org.dromara.creditcard.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.creditcard.domain.CreditCard;
import org.dromara.creditcard.domain.CreditHolder;
import org.dromara.creditcard.service.ICreditHolderService;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.mybatis.core.page.PageUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.SysRole;
import org.dromara.system.service.ISysRoleService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;

/**
 * 信用卡持卡人列
 *
 * @author Mr.Zhou
 * @date 2023-11-29
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/credit/holder")
public class CreditHolderController extends BaseController {

    private final ICreditHolderService creditHolderService;

    private final ISysRoleService sysRoleService;

    /**
     * 查询信用卡持卡人列列表
     */
    @SaCheckPermission("credit:holder:list")
    @GetMapping("/list")
    public TableDataInfo<CreditHolder> list(CreditHolder creditHolder, PageQuery pageQuery) {
        Integer agentId = null;
        LoginUser loginUser = LoginHelper.getLoginUser();
        SysRole sysRole = sysRoleService.selectRoleByUserId(loginUser.getUserId());
        if(sysRole != null){
            if(sysRole.getRoleKey().equals("agent") || sysRole.getRoleKey().equals("business")) {
                agentId = loginUser.getAgentId();
            }
        }

        QueryWrapper<CreditHolder> qw = new QueryWrapper<>();
        if(agentId != null){
            qw.eq("agent_id", agentId);
        }else{
            if(creditHolder.getAgentId() != null){
                qw.eq("agent_id", creditHolder.getAgentId());
            }
        }

        qw.orderByDesc("id");
        TableDataInfo<CreditHolder> td = PageUtils.buildDataInfo(creditHolderService.page(PageUtils.buildPage(),qw));
        List<CreditHolder> list = td.getRows();
        return td;
    }


    /**
     * 信用卡持卡人列列表(不分页，下拉框使用)
     */
    @SaCheckPermission("credit:holder:list")
    @GetMapping("/noPage/list")
    public R<List<CreditHolder>> noPageList(CreditHolder creditHolder) {

        Integer agentId = null;
        LoginUser loginUser = LoginHelper.getLoginUser();
        SysRole sysRole = sysRoleService.selectRoleByUserId(loginUser.getUserId());
        if(sysRole != null){
            if(sysRole.getRoleKey().equals("agent") || sysRole.getRoleKey().equals("business")) {
                agentId = loginUser.getAgentId();
            }
        }

        QueryWrapper<CreditHolder> qw = new QueryWrapper<>();
        if(agentId != null){
            qw.eq("agent_id", agentId);
        }else{
            if(creditHolder.getAgentId() != null){
                qw.eq("agent_id", creditHolder.getAgentId());
            }
        }

        List<CreditHolder> list = creditHolderService.list(qw);
        return R.ok(list);
    }


    /**
     * 导出信用卡持卡人列列表
     */
    @SaCheckPermission("credit:holder:export")
    @Log(title = "信用卡持卡人列", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(CreditHolder creditHolder, HttpServletResponse response) {
        List<CreditHolder> list = creditHolderService.list();
        ExcelUtil.exportExcel(list, "信用卡持卡人列", CreditHolder.class, response);
    }

    /**
     * 获取信用卡持卡人列详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("credit:holder:query")
    @GetMapping("/{id}")
    public R<CreditHolder> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        return R.ok(creditHolderService.getById(id));
    }

    /**
     * 新增信用卡持卡人列
     */
    @SaCheckPermission("credit:holder:add")
    @Log(title = "信用卡持卡人列", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody CreditHolder creditHolder) {
        creditHolder.setCreateTime(new Date());

        LoginUser loginUser = LoginHelper.getLoginUser();
        creditHolder.setAgentId(loginUser.getAgentId());

        return toAjax(creditHolderService.save(creditHolder));
    }

    /**
     * 修改信用卡持卡人列
     */
    @SaCheckPermission("credit:holder:edit")
    @Log(title = "信用卡持卡人列", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody CreditHolder creditHolder) {
        return toAjax(creditHolderService.updateById(creditHolder));
    }

    /**
     * 删除信用卡持卡人列
     *
     * @param ids 主键串
     */
    @SaCheckPermission("credit:holder:remove")
    @Log(title = "信用卡持卡人列", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        return toAjax(creditHolderService.removeByIds(Arrays.asList(ids)));
    }
}
